import fs from "fs";
import type { IKeyItem } from "../theme/types";
import constant from "../constant";

const cwd = process.cwd();
const targetPath = `${cwd}/docs`;

const getSearchKeyToJson = () => {
	const targetDirs = getTargetDir();
	let result = {};
	targetDirs.map((dir) => {
		const files = fs.readdirSync(
			`${targetPath}/${dir}`,
			{ encoding: "utf8" }
		).filter((item) => item !== "index.md");

		const res = files.map((file) => {
			const text = file.replace(".md", "");
			const obj = {
				text,
				link: `${constant.base}/${dir}/${text}`,
			} as IKeyItem;
			return obj;
		});

		result[dir] = res
	});
	generateJsonFile(result);
};

// 获取目标文件夹
const getTargetDir = () => {
	const dirs = fs.readdirSync(targetPath, { encoding: "utf8" });
	const targetDirs = dirs.filter((item) =>
		!["index.md", ".vitepress", "public"].includes(item)
	);
	return targetDirs;
};

// 生成查询文件
const generateJsonFile = (data: any) => {
	const keysInfo = JSON.stringify({ keywords: data });
	fs.writeFile(
		`${targetPath}/.vitepress/keyWord.json`,  // 目标文件
		keysInfo,  // 写入的内容
		{ encoding: "utf8" },  // 编码格式
		(err) => {
			if (err) console.log(err);
		}
	);
};

export default getSearchKeyToJson;
